import 'package:meco/common/index.dart';
import 'package:meco/common/models/user_follow_model.dart';
import 'package:sqflite/sqflite.dart';

// 用户关注状态观察者接口
abstract class UserFollowObserver {
  // 当用户关注状态变化时调用
  void onFollowStatusChanged(int followerId, int followingId, bool isFollowing);
}

class UserFollowRepository {
  final DatabaseService _databaseService = DatabaseService();

  // 表名
  final String _tableName = 'user_follows';

  // 观察者列表
  static final List<UserFollowObserver> _observers = [];

  // 添加观察者
  static void addObserver(UserFollowObserver observer) {
    if (!_observers.contains(observer)) {
      _observers.add(observer);
      print(
        '添加UserFollowObserver: ${observer.runtimeType}, 当前观察者数量: ${_observers.length}',
      );
    }
  }

  // 移除观察者
  static void removeObserver(UserFollowObserver observer) {
    _observers.remove(observer);
    print(
      '移除UserFollowObserver: ${observer.runtimeType}, 当前观察者数量: ${_observers.length}',
    );
  }

  // 通知所有观察者关注状态变化
  static void _notifyFollowStatusChanged(
    int followerId,
    int followingId,
    bool isFollowing,
  ) {
    print(
      '通知关注状态变化: followerId=$followerId, followingId=$followingId, isFollowing=$isFollowing',
    );
    for (var observer in _observers) {
      observer.onFollowStatusChanged(followerId, followingId, isFollowing);
    }
  }

  // 关注用户
  Future<UserFollow?> followUser({
    required int followerId,
    required int followingId,
  }) async {
    try {
      print('开始执行followUser: followerId=$followerId, followingId=$followingId');

      // 检查是否已经关注过
      final existingFollow = await getFollow(followerId, followingId);
      if (existingFollow != null) {
        print('已经关注过该用户: $existingFollow');
        return existingFollow; // 已经关注过
      }

      final now = DateTime.now();
      final userFollow = UserFollow(
        followerId: followerId,
        followingId: followingId,
        createdAt: now,
        updatedAt: now,
      );

      print('准备添加关注记录: $userFollow');
      final id = await _addFollow(userFollow);
      print('关注记录添加成功，ID: $id');

      // 通知观察者
      _notifyFollowStatusChanged(followerId, followingId, true);

      return userFollow.copyWith(id: id);
    } catch (e) {
      print('关注用户错误: $e');
      return null;
    }
  }

  // 取消关注
  Future<bool> unfollowUser({
    required int followerId,
    required int followingId,
  }) async {
    try {
      final db = await _databaseService.database;
      final result = await db.delete(
        _tableName,
        where: 'follower_id = ? AND following_id = ?',
        whereArgs: [followerId, followingId],
      );

      if (result > 0) {
        // 通知观察者
        _notifyFollowStatusChanged(followerId, followingId, false);
      }

      return result > 0;
    } catch (e) {
      print('取消关注错误: $e');
      return false;
    }
  }

  // 添加关注记录
  Future<int> _addFollow(UserFollow userFollow) async {
    try {
      final db = await _databaseService.database;
      final json = userFollow.toJson();
      print('添加关注记录，JSON数据: $json');
      final id = await db.insert(_tableName, json);
      print('添加关注记录成功，返回ID: $id');
      return id;
    } catch (e) {
      print('添加关注记录失败: $e');
      rethrow; // 重新抛出异常以便上层捕获
    }
  }

  // 获取特定的关注记录
  Future<UserFollow?> getFollow(int followerId, int followingId) async {
    try {
      final db = await _databaseService.database;
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'follower_id = ? AND following_id = ?',
        whereArgs: [followerId, followingId],
      );

      if (maps.isNotEmpty) {
        final follow = UserFollow.fromJson(maps.first);
        return follow;
      }
      return null;
    } catch (e) {
      print('查询关注记录失败: $e');
      return null;
    }
  }

  // 检查是否已关注
  Future<bool> isFollowing(int followerId, int followingId) async {
    try {
      final follow = await getFollow(followerId, followingId);
      final result = follow != null;
      return result;
    } catch (e) {
      return false;
    }
  }

  // 获取用户的关注列表（该用户关注的人）
  Future<List<User>> getFollowingUsers(int userId) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.rawQuery(
      '''
      SELECT u.* FROM users u
      INNER JOIN $_tableName f ON u.id = f.following_id
      WHERE f.follower_id = ?
    ''',
      [userId],
    );

    return List.generate(maps.length, (i) {
      return User.fromJson(maps[i]);
    });
  }

  // 获取用户的粉丝列表（关注该用户的人）
  Future<List<User>> getFollowerUsers(int userId) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.rawQuery(
      '''
      SELECT u.* FROM users u
      INNER JOIN $_tableName f ON u.id = f.follower_id
      WHERE f.following_id = ?
    ''',
      [userId],
    );

    return List.generate(maps.length, (i) {
      return User.fromJson(maps[i]);
    });
  }

  // 获取用户的关注数量
  Future<int> getFollowingCount(int userId) async {
    final db = await _databaseService.database;
    final result = await db.rawQuery(
      '''
      SELECT COUNT(*) as count FROM $_tableName
      WHERE follower_id = ?
    ''',
      [userId],
    );
    return Sqflite.firstIntValue(result) ?? 0;
  }

  // 获取用户的粉丝数量
  Future<int> getFollowerCount(int userId) async {
    final db = await _databaseService.database;
    final result = await db.rawQuery(
      '''
      SELECT COUNT(*) as count FROM $_tableName
      WHERE following_id = ?
    ''',
      [userId],
    );
    return Sqflite.firstIntValue(result) ?? 0;
  }
}
